﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;

namespace TireService.Web.View.ServiceView
{
    public partial class Preparation : System.Web.UI.Page
    {
        #region Public Properties

        public List<int> Printlabels
        {
            get
            {
                if (ViewState["_printlabelse"] != null)
                    return (List<int>)ViewState["_printlabelse"];
                else
                    return null;
            }
            set
            {
                ViewState["_printlabelse"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Bind data to container dropdownlist
            ddlContainer.DataSource = db.GetContainers();
            ddlContainer.ValueField = "ContainerId";
            ddlContainer.TextField = "ContainerNumber";
            ddlContainer.DataBind();

            if (Page.IsPostBack != true)
            {
                // Select first record i dropdownlists
                ddlContainer.SelectedIndex = 0;
                
                // Set today as value for scheduledate
                calScheduleDate.Value = DateTime.Now;
            }

            // Bind container data to gridview
            BindServiceCarSchedulePackingData(db, Convert.ToInt32(ddlContainer.Value), Convert.ToDateTime(calScheduleDate.Value));

            // Change gridview pagesize based on dropdownlist
            gvServiceCarSchedulePacking.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind servicecarschedule packing list data to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="ContainerId">Id on container where packinglist is related to</param>
        /// <param name="Scheduledate">Packing list for schedule date</param>
        private void BindServiceCarSchedulePackingData(TireServiceDB db, int ContainerId, DateTime ScheduleDate)
        {
            gvServiceCarSchedulePacking.DataSource = db.ServiceCarSchedulePackingViews.Where(p => p.ContainerId == ContainerId & p.CarId != null & p.ScheduleDate == ScheduleDate).ToList();
            gvServiceCarSchedulePacking.DataBind();

            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        #region Private Functions

        /// <summary>
        /// Function that prints servicecarschedules for selected date, container and all employees
        /// </summary>
        private void PrintServiceCarSchedules()
        {
            // Go to report
            Response.Redirect("~/Reports/View/ServiceCarScheduleReportView.aspx?ContainerId=" + ddlContainer.Value.ToString() + "&ScheduleDate=" + calScheduleDate.Value.ToString());
        }

        /// <summary>
        /// Function that change grouping in order gridview
        /// </summary>
        /// <param name="ViewIndex">Integer setting the grouping mode</param>
        protected void GroupOrderData(int ViewIndex)
        {
            gvServiceCarSchedulePacking.ClearSort();
            gvServiceCarSchedulePacking.GroupSummary.Clear();
            switch (ViewIndex)
            {
                case 0:
                    gvServiceCarSchedulePacking.GroupBy(gvServiceCarSchedulePacking.Columns["ServiceCarDescription"]);

                    break;
                case 1:
                    gvServiceCarSchedulePacking.GroupBy(gvServiceCarSchedulePacking.Columns["CargoRoomNumber"]);

                    break;
                //case 3:
                //    gvOrder.GroupBy(gvOrder.Columns["PhotoDate"]);
                //    gvOrder.GroupBy(gvOrder.Columns["CustomerNumber"]);

                //break;
            }
            gvServiceCarSchedulePacking.ExpandAll();
        }

        #endregion

        #region Control Functions

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.Value == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.Value == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.Value == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.Value == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        
        /// <summary>
        /// Dropdown list function that change gridview grouping when selected item is changed
        /// </summary>
        protected void ddlView_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Group data
            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        #endregion


        #region GridView Functions

        /// <summary>
        /// Gridview function that handles edit selection of container
        /// </summary>
        protected void gvServiceCarSchedulePacking_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            //if (e.ButtonID == "Edit")
            //{
            //    try
            //    {
            //        //// Get containerid
            //        //object cellContainerId = gvServiceCarSchedulePacking.GetRowValues(e.VisibleIndex, "ContainerId");
                    
            //        //// Go to edit mode
            //        //Session["ContainerId"] = Convert.ToInt32(cellContainerId);
            //        //Response.Redirect("~/Casehandling/EditContainer.aspx");
            //    }
            //    catch (Exception ex)
            //    {
            //        if ((ex) is ArgumentException)
            //        {
            //            // User error - arguments not valid - show error message
            //            lMessage.Text = ((ArgumentException)ex).Message;
            //        }
            //        else
            //        {
            //            // System error - show general error message
            //            lMessage.Text = "Fejl opstod - venligst prøv igen";
            //        }
            //    }
            //    finally
            //    {
            //        // Update message panel
            //        upMessage.Update();
            //    }
            //}
        }

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvServiceCarSchedulePacking_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn TireDimensions: Show TireDimensions
            if (e.Column.FieldName == "TireDimensions")
            {
                // Get dimensions
                string width = Convert.ToString(e.GetListSourceFieldValue("Width"));
                string height = Convert.ToString(e.GetListSourceFieldValue("Height"));
                string size = Convert.ToString(e.GetListSourceFieldValue("Size"));

                // Change field value
                e.Value = width + " / " + height + " " + size; 
            }

            //// Format UnBoundColumn UsedCapacity: Show used capacity
            //if (e.Column.FieldName == "UsedCapacity")
            //{
            //    // Get containerid
            //    int containerid = Convert.ToInt32(e.GetListSourceFieldValue("ContainerId"));

            //    TireServiceDB db = new TireServiceDB();

            //    // Change field value
            //    e.Value = db.GetContainerUsedCapacity(containerid).First().UsedCapacity.ToString();

            //    db.Dispose();
            //}

            //// Format UnBoundColumn FreeCapacity: Show free capacity
            //if (e.Column.FieldName == "FreeCapacity")
            //{
            //    // Get containerid
            //    int containerid = Convert.ToInt32(e.GetListSourceFieldValue("ContainerId"));

            //    TireServiceDB db = new TireServiceDB();

            //    // Change field value
            //    e.Value = db.GetContainerFreeCapacity(containerid).First().FreeCapacity.ToString();

            //    db.Dispose();
            //}
        }

        protected void gvServiceCarSchedulePacking_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();
            
            // Bind container data to gridview
            BindServiceCarSchedulePackingData(db, Convert.ToInt32(ddlContainer.Value), Convert.ToDateTime(calScheduleDate.Value));
        }

        #endregion

        //protected void ddlContainer_SelectedIndexChanged(object sender, EventArgs e)
        //{

        //}

        protected void calScheduleDate_DayRender(object sender, DevExpress.Web.ASPxEditors.DayRenderEventArgs e)
        {
            try
            {
                TireServiceDB db = new TireServiceDB();

                // Check if schedule exists on this date for this container - if then highlight date
                if (db.ScheduleDateExistsOnContainer(Convert.ToInt32(ddlContainer.Value), Convert.ToDateTime(e.Day.DateTime)))
                {
                    e.Style.BackColor = System.Drawing.Color.Blue;
                }

                db.Dispose();
            }
            catch (Exception ex)
            {

            }
        }

    }
}